package client;

import java.io.IOException;

import client.ClientLib.ClientType;
import client.ClientLib.FailedConnectException;

public class PubRandom {

	public static void main(String[] args) {
		String host = args.length > 0 ? args[0] : "localhost";
		int port = args.length > 1 ? Integer.parseInt(args[1]) : 15000;
		String pubId = args.length > 2 ? args[2] : "random";
		final int TIME = args.length > 3 ? Integer.parseInt(args[3]) * 1000 : 5000;
		final int RATE = args.length > 4 ? Integer.parseInt(args[4]) : 8;

		int kilobytes = (RATE * 1000) / 8;
		int delayMill = 1000 / kilobytes;
		int delayNano = (int) (1000000 * (1000. / kilobytes - delayMill));

		ClientLib client = new ClientLib(pubId, host, port, ClientType.PUBLISHER);
		try {
			client.connect();
			Thread.sleep(5000);
		}
		catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		catch (FailedConnectException e) {
			System.exit(-1);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}

		long start = System.currentTimeMillis();
		byte[] data = new byte[1024];
		int sent = 0;
		while (System.currentTimeMillis() < start + TIME) {
			for (int i = 0; i < data.length; i++)
				data[i] = (byte) (int) (16 * Math.random());

			try {
				client.publish(data);
				sent++;
				Thread.sleep(delayMill, delayNano);
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		double thru = (sent * 8) / ((end - start) / 1000.0);
		System.out.printf("Sent: %d kB in %d msec (%.1f kbps)\n", sent, end - start, thru);
	}
}
